package ch02;

public class SequenceNumber {

	// 定义匿名子类创建ThreadLocal 的变量
	private ThreadLocal<Integer>  seqNum = new ThreadLocal<Integer>(){
		
		// override初始化方法
		@Override
		public Integer initialValue(){
			return 0;
		}
	};
	
	private ThreadLocal<Integer>  threadLocal2 = new ThreadLocal<Integer>();
	
	public int getNextNum(){
		seqNum.set(seqNum.get() + 1);
		threadLocal2.set(seqNum.get() -1);
		return seqNum.get();
	}
	
	private static class TestClient extends Thread{
		
		private SequenceNumber sn;
		
		public TestClient(SequenceNumber sn){
			this.sn = sn;
		}
		
		@Override
		public void run(){
			for (int i = 0; i < 3; i++) {
				System.out.println("thread[" + Thread.currentThread().getName() + "] sn[" + sn.getNextNum() + "]" );
			}
		}
		
	} 
	
	public static void main(String[] args) {
		SequenceNumber sn = new SequenceNumber();
		// 三个线程产生各自的序列号
		TestClient t1 = new TestClient(sn);
		TestClient t2 = new TestClient(sn);
		TestClient t3 = new TestClient(sn);
		t1.start();
		t2.start();
		t3.start();
	}
}